<template>
  <div class="selected">
    <van-field
      v-model="resultLabel"
      v-bind="$attrs"
      readonly
      is-link
      input-align="right"
      @click="showPopu($attrs.disabled)"
      class="box-item "
    />
    <van-popup v-model="show" round  position="bottom">
      <van-picker
        v-bind="$attrs"
        :columns="columnsData"
        show-toolbar
        @cancel="show = false"
        @confirm="onConfirm"
        :value-key="this.option.label"
      />
    </van-popup>
  </div>
</template>

<script>
import { Field , Popup , Picker  } from 'vant';

export default {
  name: 'selected',
  components: {
    [Field .name]: Field,
    [Popup.name]: Popup,
    [Picker .name]: Picker,
  },
  model: {
    prop: 'selectValue'
  },
  props: {
    columns: {
      type: Array,
      default: function () {
        return []
      }
    },
    selectValue: {
      type: [String, Number],
      default: ''
    },
    option: {
      type: Object,
      default: function () {
        return { label: 'label', value: 'value' }
      }
    },
    offOption: { // 关闭option配置key-value;当数据是非集合的数组的时候，开启
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      show: false,
      resultValue: this.selectValue,
      columnsData: []
    }
  },
  computed: {
    resultLabel: {
      get () {
        const res = this.columns.filter(item => {
          const data = this.offOption ? item : item[this.option.value]
          return data === this.resultValue
        })
        let label = ''
        if (res.length) {
          label = this.offOption ? res[0] : res[0][this.option.label]
        }

        return label
      },
      set () {

      }
    }
  },
  watch: {
    selectValue: function (newVal) {
      this.resultValue = newVal
    },
    resultValue (val) {
      this.columnsData = JSON.parse(JSON.stringify(this.columns))
    }
  },
  methods: {
    onConfirm (value, index) {
      const data = this.offOption ? value : value[this.option.value]
      this.resultValue = data
      this.show = false
      this.$emit('confirm', value, index, this.resultValue)
    },
    showPopu (disabled) {
      this.columnsData = JSON.parse(JSON.stringify(this.columns))
      this.resultValue = this.selectValue
      if (disabled !== undefined && disabled !== false) {
        return false
      } else {
        this.show = true
      }
    }
  },

}
</script>

<style lang="less" scoped>
.selected{
  margin-bottom: 10px;
  position: relative;
}
.selected::after{
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 0.426667rem;
    bottom: 0;
    left: 0.426667rem;
    border-bottom: 0.026667rem solid #ebedf0;
    -webkit-transform: scaleY(.5);
    transform: scaleY(.5);
}
.van-cell::after{
  border-bottom: 0;
}
</style>
